<template>
<div class="wrapper">

    <div class="tip">
        <svg @click="goBack()" t="1743402074255" class="backIcon" viewBox="0 0 1024 1024" version="1.1"
            xmlns="http://www.w3.org/2000/svg" p-id="2913" width="20" height="20">
            <path
                d="M739.555556 198.599111L412.842667 525.312 739.555556 852.024889l-84.821334 84.764444-411.534222-411.477333L654.791111 113.777778z"
                fill="#fff" p-id="2914">
            </path>
        </svg>
        浏览历史
        <div v-if="newsList != null && newsList.length != 0" style="right: 25px;height: 20px;position: absolute;">
            <div v-if="HistoryPageStatus=='check'" @click="HistoryPageStatus='delete'">
                <el-icon size="20"><Edit /></el-icon>
            </div>
            <div v-else @click="{HistoryPageStatus='check';checkedItems=[];}">
                <p>完成</p>
            </div>
        </div>
    </div>

    <div v-if="newsList != null && newsList.length != 0" class="category-news-list">
        <div v-for="news in newsList" :key="news.title" class="list-item" @click="HistoryPageStatus!='delete' && navigateToNewsDetails(news)">
            <!--复选框-->
            <div v-if="HistoryPageStatus=='delete'" class="favorites-item-checkbox">
                <input type="checkbox" :checked="checkedItems.includes(news.id)" @change="selectAllOne(news)"/>
            </div>
            <img v-if="news.frontCover" :src="news.frontCover" width="80" height="60" style="border-radius: 6px; object-fit: cover;">
            <div class="list-item-content">
                <div class="list-item-title">{{ news.title }}</div>
                <div class="list-item-subtitle" style="display: flex;justify-content: space-between;">
                    {{ getNewsCategoriesName(news.categoryId) }} · {{ news.publishTime }}
                    <div @click.stop="handleClickEllipsis(news)"><i class="fa-solid fa-ellipsis-vertical"></i></div>
                </div>
            </div>
        </div>
    </div>

    <div v-else style="text-align: center; font-size:16px; margin-top: 20px;">
        ———您还没有浏览历史，快去浏览吧~ ———
    </div>


    <!-- 底部操作栏 -->
    <div v-if="HistoryPageStatus=='delete'" class="favorites-actions">
        <div class="favorites-action-button favorites-action-select-all" @click="selectAll()">
            {{ checkedItems.length === newsList.length ? '取消全选' : '全选' }}
        </div>
        <div class="favorites-action-button favorites-action-delete" @click="deleteItems()">
            删除
        </div>
    </div>


    <!--隐藏的对话框-->
          <!--评论操作对话框-->
    <el-dialog v-model="dialogOperateHistoryVisible" title="" width="100%" style="margin-bottom: 0;padding-bottom: 40px;"align-center>
        <el-card @click="confirmDeleteHistoryVisible = true" style="margin-top: 20px;">
        <span style="display: flex;align-items: center;gap: 10px;">
            <el-icon><Delete /></el-icon>
            <p>删除</p>
        </span>
        </el-card>
    </el-dialog>
          <!--确认删除浏览历史对话框-->
    <el-dialog v-model="confirmDeleteHistoryVisible" title="" width="90%" center align-center>
        <div style="width: 100%;text-align: center;">确认删除吗？</div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="confirmDeleteHistoryVisible = false">取消</el-button>
                <el-button type="primary" @click="DeleteHistory()">确认</el-button>
            </div>
        </template>
    </el-dialog>

</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, inject } from 'vue'
import { useRouter } from 'vue-router';
import api from '@/api';
import { NewsStore } from '@/stores/newsInfoStore';
import { UserStore } from '@/stores/userInfoStore';
import { TipStore } from '@/stores/tipStore';

const disableCacheFor = inject('disableCacheFor') as (componentNameList: string[]) => void;
const router = useRouter();
const newsStoreObject = NewsStore();
const userStoreObject = UserStore();
const TipStoreObject = TipStore();

const newsList = ref([])


// 数据定义
const News_queryDTO = ref({
    categoryId: null,
    status: 1,

    current: 1,
    size: 20,
})


// 获取新闻分类名称
const getNewsCategoriesName = (Id) => {
    if (Id != null) {
        return newsStoreObject.newsCategoryInfo.find(ncInfo => ncInfo.id == Id)?.name;
    } else { return null }
};

//跳转新闻详情
const navigateToNewsDetails = (news) => {
    router.push({
        path: '/NewsDetails',
        query: {
            NewsId: news.id,
            newsCategoryName: getNewsCategoriesName(news.categoryId)
        }
    });
};


//#region 关于复选框
const HistoryPageStatus = ref('check') //['check','delete']
const checkedItems = ref([]);

//单选
const selectAllOne = (item) => {
    const isChecked = checkedItems.value.includes(item.id);
    if (isChecked) {
        checkedItems.value = checkedItems.value.filter((i) => i !== item.id);
    } else {
        checkedItems.value.push(item.id);
    }
};
//全选
const selectAll = () => {
    if (checkedItems.value.length === newsList.value.length) {
        checkedItems.value = [];
    } else {
        checkedItems.value = newsList.value.map(item => item.id);
    }
};

//删除按钮
const deleteItems = async() => {
    let res = confirm("删除后不可恢复，确认删除吗？")
    if(!res){
        return
    }
    await api.deleteHistory(checkedItems.value, userStoreObject.userInfo.id).then((res)=>{
        if(res.data.code == 1){
            TipStoreObject.successTip('删除成功')
            newsList.value = newsList.value.filter(news => !checkedItems.value.includes(news.id)) // 删除成功后从数组中删除该新闻
            checkedItems.value = []
            disableCacheFor(['Profile']) //刷新组件的挂载，因为数据更新了
        }else{
            TipStoreObject.errorTip('删除失败，请稍后再试')
        }
    }).catch((err)=>{
        TipStoreObject.errorTip('删除失败，请稍后再试')
    })
};
//#endregion


//#region 操作对话框
const dialogOperateHistoryVisible = ref(false) // 操作对话框显示标识符
const handleClickEllipsis = (news)=>{
    dialogOperateHistoryVisible.value = true
    tempHistoryId.value = news.id
}

//#endregion


//删除浏览历史记录
const tempHistoryId = ref(0)
const confirmDeleteHistoryVisible = ref(false); //确认删除对话框显示标识符

async function DeleteHistory(){
    confirmDeleteHistoryVisible.value = false
    dialogOperateHistoryVisible.value = false
    await api.deleteHistory(tempHistoryId.value, userStoreObject.userInfo.id).then((res)=>{
        if(res.data.code == 1){
            TipStoreObject.successTip('删除成功')
            newsList.value = newsList.value.filter(news => news.id != tempHistoryId.value) // 删除成功后从数组中删除该新闻
            disableCacheFor(['Profile']) //刷新组件的挂载，因为数据更新了
        }else{
            TipStoreObject.errorTip('删除失败，请稍后再试')
        }
    }).catch((err)=>{
        TipStoreObject.errorTip('删除失败，请稍后再试')
    })
}


const goBack = () => {
    router.back();
}


onMounted(async () => {
    if(userStoreObject.userInfo.id){
        api.getNewsByUserHistory(userStoreObject.userInfo.id, News_queryDTO.value.current, News_queryDTO.value.size).then(res => {
            newsList.value.push(...res.data.data)
        })
    }
})

</script>

<style lang="scss" scoped>
@mixin CommonStyle-center {
    display: flex;
    justify-content: center;
    align-items: center;
}
.wrapper{
    min-width: 350px
}

.tip {
    @include CommonStyle-center;
    top: 0;
    background-color: #409eff;
    color: #fff;
    height: 60px;
    min-height: 60px;
    position: relative;
}

.backIcon {
    position: absolute;
    left: 10px;
}

.favorites-item-checkbox {
    margin-right: 5px;
}
.favorites-item-checkbox input[type='checkbox'] {
    width: 20px;
    height: 20px;
}

.category-news-list {
    margin-top: 16px;
}

.list-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 10px 30px;
    border-bottom: 1px solid #eaeaea;
    cursor: pointer;
}

.list-item-content {
    flex: 1;
    margin-left: 16px;
    width: 75%;
}

.list-item-title {
    font-weight: 600;
    font-size: 16px;
    margin-bottom: 15px;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
}

.list-item-subtitle {
    color: #8e8e93;
    font-size: 14px;
}

.favorites-actions {
    display: flex;
    justify-content: space-between;
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #eaeaea;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
}
.favorites-action-button {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    border-radius: 8px;
    font-weight: 600;
}
.favorites-action-select-all {
    background-color: #f2f2f7;
    color: #007aff;
    margin-right: 8px;
}
.favorites-action-button {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    border-radius: 8px;
    font-weight: 600;
}
.favorites-action-delete {
    background-color: #ff3b30;
    color: white;
}
</style>